﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace clawPDF.HttpService.API.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class FilesController : ControllerBase
    {
        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="files"></param>
        /// <returns></returns>
        [HttpPost("uploadfiles")]
        public async Task<IActionResult> UploadFiles()
        {
            var files = HttpContext.Request.Form?.Files;
            if (!files.Any())
                return BadRequest();
            //文件名称冲突时添加版本号，true添加  false覆盖原文件
            var ensureUniqueFilenames = Convert.ToBoolean(HttpContext.Request.Form?["EnsureUniqueFilenames"].ToString() ?? "false");

            long size = files.Sum(f => f.Length);

            var basePath = @"D:\UploadingFiles\";
            foreach (var formFile in files)
            {
                await SaveFile(formFile, basePath, ensureUniqueFilenames);
            }

            return Ok(new { count = files.Count, size });
        }


        private async Task SaveFile(IFormFile formFile, string basePath, bool ensureUniqueFilenames)
        {
            if (!Directory.Exists(basePath))
                Directory.CreateDirectory(basePath);

            var filePath = basePath + formFile.FileName;

            if (formFile.Length > 0)
            {
                if (System.IO.File.Exists(filePath))
                {
                    if (!ensureUniqueFilenames)
                    {
                        System.IO.File.Delete(filePath);
                    }
                    else
                    {
                        filePath = this.GetNewFilePath(basePath, formFile.FileName);
                    }
                }
                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await formFile.CopyToAsync(stream);
                }
            }
        }

        private string GetNewFilePath(string basePath, string fileName, int v = 1)
        {
            //test.pdf
            string fileNamePrefix = Path.GetFileNameWithoutExtension(fileName);//获取文件名称，不带后缀名 test
            var newFileName = fileNamePrefix + $"_{v}";
            var filePath = basePath + fileName.Replace(fileNamePrefix, newFileName);
            if (System.IO.File.Exists(filePath))
            {
                return GetNewFilePath(basePath, fileName, v + 1);
            }
            return filePath;
        }
    }


    public class FileUploads_IM
    {
        public bool EnsureUniqueFilenames { get; set; }
        public List<IFormFile> Files { get; set; }
    }
}
